/**
* @Title: caseAuditList_Ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @date 2014年10月27日 下午4:43:38
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('CaseAuditListCtrl', ['$scope','$state','$modal','CaseCommonService','CaseAuditListService','CaseAuditProjectAddService','BaseURL','Modal',
	                                     'FwaTabsetService','InsuranceService','AuditDictServices','CommunityService',
	                                function($scope,$state,$modal,CaseCommonService,caseAuditListService,CaseAuditProjectAddService,baseUrl,Modal,
	                                		fwaTabsetService,InsuranceService,AuditDictServices,CommunityService){
		
		$scope.addOnClick = function(){
			fwaTabsetService.selectTab('caseAudit.caseAuditAdd',null,false);
		}
		
		InsuranceService.initMedicalOrgInfoList().success(function(response){
            $scope.medicalOrgInfoList = response.medicalOrgList;
		});
		
		$scope.auditDictServices = AuditDictServices;
		AuditDictServices.initCodeListDatas();
        $scope.communityService = CommunityService;
        CommunityService.initCodeListDatas();
        var cellTemplate =
        	'<a ng-show="data.market ==3 || data.market == 5"  ng-click="cancelAudit(data);">撤回</a>' +
        	'<a ng-show="data.market ==0 "  ng-click="showOperation(data);">查看</a>' +
            '<a ng-show="data.market ==1" ng-click="operation(data);">稽核</a>' +
            '<a ng-show="data.market == 2" ng-click="operationDispathch(data);">复核</a>';
		$scope.columns = [
		{
			label : '案件号',
			map : 'caseCode',
			width : '15%',
			 cellTemplate:'<a  ng:bind="data.caseCode" '+
           'ng-click="queryAuditCase(data)"></a>'},
		{
			label : '机构名称',
			map : 'orgName',
			width : '20%'
		}, {
			label : '受理时间',
			map : 'auditDate',
			width : '10%'
		}, {
			label : '不合理费用',
			map : 'totalDeduction',
			width : '15%'
		}, {
			label : '告知时间',
			map : 'notifyDate',
			width : '10%'
		}, {
			label : '机构确认时间',
			map : 'affirmDate',
			width : '10%'
		}, {
			label : '案件状态',
			map : 'statusName',
			width : '10%'
		}, {
			label : '操作',
			map : 'operation',
			width : '10%',
			cellTemplate:cellTemplate}];

        /**
         * 稽核
         * @param data
         */
		$scope.operation = function(data){
            if(data.market=="1" && data.rollbackFlag==1)
            {
                $state.go('caseAudit.caseAuditBackProject',{caseCode:data.caseCode,problemNo:data.relatedCode,urlFlag:''});
            }else
            {
                $state.go('caseAudit.caseAuditProject',{caseCode:data.caseCode,problemNo:data.relatedCode,urlFlag:''});
            }
		}
		/**
		 * 稽核撤回
		 * @param data
		 */
		$scope.cancelAudit = function(data){
			$state.go('caseAudit.caseAuditCancel',{caseCode:data.caseCode,problemCode:data.relatedCode,
				backFlag:'caseAudit.caseAuditList',caseStatus:data.caseStatus});
		}
        /**
         * 复核
         * @param data
         */
        $scope.operationDispathch=function(data)
        {
            if(data.market=="2" && data.rollbackFlag==1)
            {
                $state.go('caseAudit.caseReviewBackProject',{caseCode:data.caseCode,problemNo:data.relatedCode,urlFlag:''});
            }else
            {
                $state.go('caseAudit.caseReviewProject',{caseCode:data.caseCode,problemNo:data.relatedCode,urlFlag:''});
            }
        }
        /**
         * 查看
         * @param data
         */
        $scope.showOperation=function(data)
        {
            $scope.queryAuditCase(data);
        }
        $scope.queryAuditCase = function(data){
            $state.go("caseDetailView.detail",{caseCode:data.caseCode,problemCode:data.relatedCode});
        }

		$scope.onReset = function(){
            $scope.params.caseCode=null;
            $scope.params.orgName=null;
            $scope.params.auditDate={start:null,end:null};
            $scope.params.sourceType=null;
            $scope.params.doctorName=null;
            $scope.params.jobLicense=null;
            $scope.params.sbmitDate={start:null,end:null};
	        };
	        
            $scope.currentPage = 1;
            var start = 0;
            $scope.limit = 20;
            $scope.params = {
                page:0,
                pageSize:20
            };

            //分页监听
            $scope.$on('pageTool.skipPage',function(e,v){
                $scope.currentPage = v;
                start = $scope.limit*(v-1);
                $scope.onSubmit(true);
            });
        /**
	     * 
	     **/
	    $scope.onSubmit = function(resetPage){
            
            $scope.params.page=0;
            
            if(resetPage == null || !resetPage){
	    		$scope.currentPage= 1;
	    		$scope.params.page = 0; 
	    	}else{
    			$scope.params.page = ($scope.currentPage - 1) * 20;
	    	}
            
            
            var fparam = $scope.params;
            if($scope.params.auditDate){
                var start = $scope.params.auditDate.start;
                var end = $scope.params.auditDate.end;
                fparam.beginDate = start;
                fparam.endDate = end;
            }
            if($scope.params.sbmitDate){
                var start = $scope.params.sbmitDate.start;
                var end = $scope.params.sbmitDate.end;
                fparam.start = start;
                fparam.end = end;
            }
	    	fparam.caseStatus="\'2\',\'3\'";
            CaseCommonService.loadCaseAuditTask(fparam).success(function(rst){
                if(rst){
                    $scope.tableData = rst.root;
                    $scope.totalCount = rst.total;
                }
	    	});
	    }


        var checkRows = [];
        function findCheck(d) {
            for(var i=0;i< checkRows .length;i++) {
                var checkedData =  checkRows [i];
                if(checkedData.caseCode == d.caseCode) {
                    return i;
                }
            }
            return -1;
        }

        $scope.$on('fwatable.checked', function(e,d){
            if(findCheck(d) == -1) {
                checkRows .push(d);
            }
        });

        $scope.$on('fwatable.unchecked', function(e,d){
            var index = findCheck(d);
            if(index != -1) {
               checkRows.splice(index,1);
            }
        });
    /**
     *  批量操作（稽核）
     */
    $scope.loading = false;
    $scope.onBatchOperateDc = function(){
        var caseCodes = [];
        if(checkRows.length == 0){
            Modal.alert('请选择需要操作的选项！');
            return;
        }else{
            //验证勾选项是否全为稽核
            for ( var i = 0; i < checkRows.length; i++) {
                if (checkRows[i].market != 1) {
                    Modal.alert('只能选择同一状态进行批量操作！');
                    return;
                }
                caseCodes.push(checkRows[i].caseCode);
            }
            $scope.loading = true;
            var param={caseCodes:caseCodes};
            CaseAuditProjectAddService.addBatchCaseInfo(param).success(function(rst){
                if(rst.state){
                    Modal.alert(rst.msg);
                    $scope.onSubmit();
                }
                $scope.loading = false;
            });

        }
    }
    /****************** 一下处理日期的函数,目的是获取t+5日期*******************/
    Date.prototype.format = function(format)
    {
        var o = {
            "M+" : this.getMonth()+1, //month
            "d+" : this.getDate(),    //day
            "h+" : this.getHours(),   //hour
            "m+" : this.getMinutes(), //minute
            "s+" : this.getSeconds(), //second
            "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
            "S" : this.getMilliseconds() //millisecond
        }

        if(/(y+)/.test(format))
        {
            format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o)
        {
            if(new RegExp("("+ k +")").test(format))
            {
                format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
            }
        }
        return format;
    }

    var currentDate= new Date();
    currentDate.setDate(currentDate.getDate()+5);
    var currentDeadLine = currentDate.format('yyyy-MM-dd');

    /**********************************************************/

    /**
     *  批量操作（复核）
     */

    $scope.onBatchOperate=function()
    {
        $scope.caseCodes = [];
        if(checkRows.length == 0){
            Modal.alert('请选择需要操作的选项！');
            return;
        }else{
            //验证勾选项是否全为复核
            for ( var i = 0; i < checkRows.length; i++) {
                if (checkRows[i].market != 2) {
                    Modal.alert('只能选择同一状态进行批量操作！');
                    return;
                }
                $scope.caseCodes.push(checkRows[i].caseCode);
            }

            var scope = $scope.$new();
            $modal.open({
                templateUrl:baseUrl+'views/hcpms/audit/batchCaseAudit.html',
                backdrop:'static',
                size:'sm',
                scope:scope,
                controller: function($scope, $modalInstance,Modal,CaseAuditProjectAddService){
                    $scope.showDeadLine=false; //展现截止日期的按钮
                    $scope.reviewDatail={};
                    //确定事件
                    $scope.confirm = function() {
                        if(check())
                        {
                            $scope.loading = true;
                            $scope.reviewDatail.caseCodes=$scope.caseCodes;
                            var param=$scope.reviewDatail;
                         CaseAuditProjectAddService.addBatchCaseReview(param).success(function(rst){
                                if(rst.state){
                                    Modal.alert(rst.msg);
                                    $scope.onClose();
                                    $scope.onSubmit();
                                }
                             $scope.loading = false;
                            });
                        }
                    }
                    function check(){
                        if(!$scope.reviewDatail.opinion){
                            Modal.alert('复核意见为必填项！');
                            return false;
                        }
                        if($scope.reviewDatail.opinion && $scope.reviewDatail.opinion=='1') { //同意
                            if (!$scope.reviewDatail.affirmDeadline) {
                                Modal.alert('截止日期为必填项！');
                                return false;
                            }
                        }
                        if(!$scope.reviewDatail.opinionDesc){
                            Modal.alert('意见说明为必填项！');
                            return false;
                        }
                        return true;
                    }
                    /**复合意见选择监听函数***/
                    $scope.selectChangeFun=function(){
                        if($scope.reviewDatail){
                            var opinion=$scope.reviewDatail.opinion;
                            if(opinion && opinion=='1'){ //同意
                                $scope.showDeadLine=true;
                                $scope.reviewDatail.affirmDeadline=currentDeadLine;
                            }else if(opinion && opinion=='0'){ //保留意见
                                $scope.showDeadLine=false;
                            }
                        }
                    }
                    //关闭弹窗
                    $scope.onClose = function() {
                        $modalInstance.dismiss();
                    }
                }
            });
        }
    }
     $scope.onSubmit();
	// end line	
	}]);
})();
